﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PS3Helpers;
using PS3Helpers.Helpers;
using System.IO;

namespace PS3Packager
{
    public class PackageGeneratorThread : ThreadBase
    {
        private readonly bool _buildFirst;
        private readonly OutputLogInterface _logInterface;
        private readonly PS3PackageFile _packageFile;

        public PackageGeneratorThread(OutputLogInterface loginterface, bool buildfirst, PS3PackageFile packagefile)
        {
            _logInterface = loginterface;
            _buildFirst = buildfirst;
            _packageFile = packagefile;
        }

        protected override void Execute()
        {
            if (string.IsNullOrEmpty(_packageFile.Filename))
                throw new Exception("Can't generate package before package file has been saved.");

            string signedElfFilename = null;
            if (_buildFirst)
            {
                PS3Builder builder = new PS3Builder(_logInterface, _packageFile, true, null);
            }

            string packagefilename = Path.ChangeExtension(_packageFile.Filename, ".pkg");
            PS3PackageCreator packager = new PS3PackageCreator(_logInterface, _packageFile, packagefilename, signedElfFilename);


            if (!string.IsNullOrEmpty(packagefilename))
            {
                if (Properties.Settings.Default.LocalPkgAutomaticallyCopy && (!string.IsNullOrEmpty(Properties.Settings.Default.LocalPkgFolder)))
                {
                    PackageUploadThread uploadthread = new PackageUploadThread(_logInterface, packagefilename, Properties.Settings.Default.LocalPkgFolder);
                    uploadthread.Start();
                    WaitForOtherThread(uploadthread);
                }

                if (Properties.Settings.Default.PS3AutomaticallyCopy && (!string.IsNullOrEmpty(Properties.Settings.Default.PS3FtpUri)))
                {
                    Uri uri = new Uri(Properties.Settings.Default.PS3FtpUri);

                    PackageUploadThread uploadthread = new PackageUploadThread(_logInterface, packagefilename, uri);
                    uploadthread.Start();
                    WaitForOtherThread(uploadthread);
                }
            }
        }
    }
}
